package com.xiaohe.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.xiaohe.common.constant.AuthServerConstant;
import com.xiaohe.common.exception.BizCodeEnum;
import com.xiaohe.common.utils.R;
import com.xiaohe.common.utils.RandomUtil;
import com.xiaohe.common.vo.MemberResponseVo;
import com.xiaohe.gulimall.authserver.feign.MemberFeignService;
import com.xiaohe.gulimall.authserver.feign.ThirdPartFeignService;
import com.xiaohe.gulimall.authserver.vo.UserLoginVo;
import com.xiaohe.gulimall.authserver.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;



    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + ":" + phone);
        if(StringUtils.isNotEmpty(redisCode)){
            long before = Long.parseLong(redisCode.split("_")[1]);
            long end = System.currentTimeMillis();
            if(end-before <60000){
                //60秒内不能进行发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码再次校验
        String code = RandomUtil.getFourBitRandom()+"_"+System.currentTimeMillis();
        //redis缓存验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX+":"+phone,code,20, TimeUnit.MINUTES);
        String sendCode = code.split("_")[0];
        //thirdPartFeignService.sendCode(phone,sendCode);
        log.info("短信发送成功，验证码为:{}",sendCode);
        return R.ok();
    }
    /**
     *
     * TODO: 重定向携带数据：利用session原理，将数据放在session中。
     * TODO:只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO：分布下session问题
     * RedirectAttributes：重定向也可以保留数据，不会丢失
     * 用户注册
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes attributes, HttpSession session){

        Map resMap = Maps.newHashMap();
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            // Map<String, Long> codeAndId = groups.stream().collect(Collectors.toMap(Group::getGroupCode, Group::getGroupId,(last,next)->next));
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,(last,next)->next));
            attributes.addFlashAttribute("errors",errors);
            //效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/regist.html";
        }

        //1、校验验证码
        String code = userRegisterVo.getCode();
        String phone = userRegisterVo.getPhone();
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + ":" + phone);
        //2、验证码去掉时间
        if(StringUtils.isNotEmpty(redisCode)){
            //分割
            //验证码对比成功
            if(redisCode.split("_")[0].equals(code)){

                //删除验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + ":" + phone);
                //验证码通过，调用远程服务注册
                R r = memberFeignService.regist(userRegisterVo);
                if(r.getCode()==0){
                    MemberResponseVo data = (MemberResponseVo) r.getData("data", new TypeReference<MemberResponseVo>() {
                    });
                    //成功,将登录信息放入到session里面
                    session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                    //注册成功回到登录页面
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    //失败
                    resMap.put("errors",r.getData("msg",new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",resMap);
                    //效验出错回到注册页面
                    return "redirect:http://auth.gulimall.com/regist.html";
                }

            }else{
                resMap.put("errors","验证码错误");
                attributes.addFlashAttribute("errors",resMap);

                //效验出错回到注册页面
                return "redirect:http://auth.gulimall.com/regist.html";
            }

        }else {
            resMap.put("errors","验证码已过期");
            attributes.addFlashAttribute("errors",resMap);

            //效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/regist.html";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo,RedirectAttributes redirectAttributes){
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() ==0){
            //成功

            //远程登录
            return "redirect:http://gulimall.com";
        }else {
            //失败
            Map maps = Maps.newHashMap();
            maps.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",maps);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute !=null){
            return "redirect:http://gulimall.com";
        }
        return "login";
    }
}
